//
//  MZTool.m
//  MZToolkitDemo
//
//  Created by Chris Yang on 2017/2/16.
//  Copyright © 2017年 Chris Yang. All rights reserved.
//

#import "MZTool.h"

@implementation MZTool

/* JSON Trandform (Obj <--> string) */
+ (id)mzJsonObjectFromString:(NSString *)jsonStr {
    
    if (nil == jsonStr) {
        return nil;
    }
    
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error = nil;
    id retObj = [NSJSONSerialization JSONObjectWithData:jsonData
                                                options:NSJSONReadingMutableContainers
                                                  error:&error];
    if(nil != error) {
        return nil;
    }
    
    return retObj;
}

+ (NSString *)mzJsonStingFromObject:(id)object {
    
    if (nil == object) {
        return nil;
    }
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if (nil != error) {
        return nil;
    }
    
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonStr;
}

#pragma mark - Current Vc

+ (UIViewController *)mzCurrentVc {
    
    UIViewController *rootVc = [UIApplication sharedApplication].delegate.window.rootViewController;
    UIViewController *curVc = [self currentVcFromVc:rootVc];
    return curVc;
}

+ (UIViewController*)currentVcFromVc:(UIViewController*)inputVc {
    
    UIViewController *curVc = inputVc;
    
    if ([inputVc isKindOfClass:[UINavigationController class]]) {
        
        UINavigationController *navVc = (UINavigationController *)inputVc;
        curVc = [self currentVcFromVc:navVc.viewControllers.lastObject];
        
    } else if ([inputVc isKindOfClass:[UITabBarController class]]) {
        
        UITabBarController* tabBarController = (UITabBarController *)inputVc;
        curVc = [self currentVcFromVc:tabBarController.selectedViewController];
        
    } else if (nil != inputVc.presentedViewController) {
        
        curVc = [self currentVcFromVc:inputVc.presentedViewController];
    }
    
    return curVc;
}

@end
